package icu.feigroup.domain.trade.service.locak.filter;

import icu.feigroup.domain.trade.adapter.repository.ITradeRepository;
import icu.feigroup.domain.trade.model.entity.GroupBuyActivityEntity;
import icu.feigroup.domain.trade.model.entity.TradeLockRuleCommandEntity;
import icu.feigroup.domain.trade.model.entity.TradeLockRuleFilterBackEntity;
import icu.feigroup.domain.trade.service.locak.factory.TradeLockRuleFilterFactory;
import icu.feigroup.types.design.framwork.link.model2.handler.ILogicHandler;
import icu.feigroup.types.enums.ResponseCode;
import icu.feigroup.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * projectName:icu.feigroup.domain.trade.service.locak.filter
 *
 * @author 飞
 * @since 2025/2/25 16:06
 * description:用户参与限制，规则过滤
 */
@Slf4j
@Service
public class UserTakeLimitRuleFilter implements ILogicHandler<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> {
    @Resource
    private ITradeRepository repository;
    @Override
    public TradeLockRuleFilterBackEntity apply(TradeLockRuleCommandEntity requestParameter, TradeLockRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("交易规则过滤-用户参与次数校验{} activityId:{}", requestParameter.getUserId(), requestParameter.getActivityId());
        GroupBuyActivityEntity groupBuyActivityEntity = dynamicContext.getGroupBuyActivityEntity();
        Integer count = repository.queryOrderCountByActivityId(requestParameter.getActivityId(),requestParameter.getUserId());
        if (groupBuyActivityEntity.getTakeLimitCount()!=null&&count>= groupBuyActivityEntity.getTakeLimitCount()){
            throw new AppException(ResponseCode.E103);
        }
        return TradeLockRuleFilterBackEntity.builder()
                .userTakeOrderCount(count)
                .build();
    }
}
